package net.quanter.shield.springboot.config;

import javax.annotation.Resource;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.quanter.shield.common.dto.result.ResultDTO;
import net.quanter.shield.common.dto.result.wapper.ResultDTOMapWrapper;
import net.quanter.shield.springboot.h2.H2Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Map;

/**
 * @author 王老实
 */
@Component("shield-BootConfig")
@Slf4j
public class BootConfig implements Serializable, CommandLineRunner {

    @Value("${runtime.debug:false}")
    @Getter
    boolean debugMode;

    @Value("${runtime.timestamp:}")
    @Getter
    String version;

    @Resource
    SpringDocProperties springDocProperties;

    @Resource
    Application application;

    @Resource
    Runtime runtime;

    @Resource
    ApplicationContext context;
    /**
     * 是否启动了H2
     */
    Object h2;

    @Getter
    private final ResultDTO<Map<String, Serializable>> configMap = ResultDTOMapWrapper.emptyMap();

    private final ResultDTOMapWrapper<String, Serializable> resultDTOMapWrapper = new ResultDTOMapWrapper(configMap);

    @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
    Object h2Config() {
        h2 = new Object();
        return h2;
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("------------------------------------------------");
        log.info("---springboot项目已启动");
        log.info("---应用信息:" + application);
        log.info("---运行环境:" + runtime);
        log.info("---构建版本:" + version);
        log.info("---您可以通过这个地址访问本项目首页:" + runtime.getIndexUrl());
        log.info("---您可以通过这个地址确认已经启动:" + runtime.getIndexUrl() + "/check");
        if (springDocProperties.isEnable()) {
            log.info("---您可以通过这个地址访问api文档:" + runtime.getIndexUrl() + "/doc.html");
        }
        if (context.containsBean("H2Config")) {
            H2Config h2Config = context.getBean(H2Config.class);
            log.info("---您可以通过这个地址访问H2数据库:" + runtime.getIndexUrl() + h2Config.getH2ConsolePath());
        }
        if (debugMode) {
            log.info("---您可以通过这个地址看到更完整的信息:" + runtime.getIndexUrl() + "/config");
            resultDTOMapWrapper.put("应用信息", application);
            resultDTOMapWrapper.put("运行环境", runtime);
            resultDTOMapWrapper.put("构建版本", version);
        }
        if (springDocProperties.apiDocsEnable) {
            resultDTOMapWrapper.put("apiDocs", springDocProperties.apiDocsPath);
        }
        log.info("------------------------------------------------");
    }
}
